<template>
  <el-dialog
    v-model="visible"
    title="更新试看状态"
    :close-on-click-modal="false"
    width="500px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        label="用户ID"
        prop="userId"
      >
        <el-input
          v-model="dataForm.userId"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="课程ID"
        prop="courseId"
      >
        <el-input
          v-model.number="dataForm.courseId"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="试看状态"
        prop="isFreeView"
      >
        <el-select
          v-model="dataForm.isFreeView"
          placeholder="请选择试看状态"
        >
          <el-option
            label="否"
            :value="0"
          />
          <el-option
            label="是"
            :value="1"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="说明">
        <el-alert
          title="提示"
          type="info"
          description="选择是否为试看状态，系统将更新该用户该课程的试看状态"
          :closable="false"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit()"
        >
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
  userId: '',
  courseId: '',
  isFreeView: 0
})

const dataRule = {
  isFreeView: [
    { required: true, message: '试看状态不能为空', trigger: 'blur' }
  ]
}

const init = (row) => {
  visible.value = true
  dataForm.userId = row.userId
  dataForm.courseId = row.courseId
  dataForm.isFreeView = row.isFreeView || 0
  dataFormRef.value?.clearValidate()
}

const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return false
    }
    http({
      url: http.adornUrl('/admin/userCourseProgress/updateFreeViewStatus'),
      method: 'post',
      params: {
        userId: dataForm.userId,
        courseId: dataForm.courseId,
        isFreeView: dataForm.isFreeView
      }
    }).then(({ data }) => {
      ElMessage.success('试看状态更新成功')
      visible.value = false
      emit('refresh-data-list')
    })
  })
}

defineExpose({
  init
})

const emit = defineEmits(['refresh-data-list', 'close'])
</script>

